package com.uy.cuantoconocesdeuruguay.dialogs;

import java.util.LinkedList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.uy.cuantoconocesdeuruguay.MainActivity;
import com.uy.cuantoconocesdeuruguay.R;
import com.uy.cuantoconocesdeuruguay.SinglePlayerImage;
import com.uy.cuantoconocesdeuruguay.datatypes.RandomImageEnvelope;
import com.uy.cuantoconocesdeuruguay.exceptions.ConnectivityException;
import com.uy.cuantoconocesdeuruguay.server.ServerConnector;
import com.uy.cuantoconocesdeuruguay.utiles.ListUtils;
import com.uy.cuantoconocesdeuruguay.utiles.SoundsUtils;
import com.uy.cuantoconocesdeuruguay.utiles.StringPool;
import com.uy.cuantoconocesdeuruguay.utiles.SystemConstants;

@SuppressLint("NewApi")
public class QuestionDialogUtils {
	private Dialog dialog;
	private RelativeLayout correct, incorrect1, incorrect2, incorrect3;
	private TextView correctTextView, incorrect1TextView, incorrect2TextView, incorrect3TextView;
	private int questionScore;
	private boolean questionAnswered;
	private TextView timerTextView, puntajeTextView;
	private RandomImageEnvelope envelope;

	private Activity activity;
	private InterstitialAd interstitial;
	private static final String SINGLE_PLAYER_INTERSITIAL_MY_AD_UNIT_ID = "ca-app-pub-2103162040664326/2834990492";
	private AsyncTask< Void, Void, Void> timerThread;
	private static final int 	GREEN = Color.argb(221, 97, 174, 36), 
								RED = Color.argb(221, 229, 64, 40), 
								GRAY = Color.rgb(233, 233, 233);
	
	public QuestionDialogUtils(Activity activity) {
		this.activity = activity;
	    interstitial = new InterstitialAd(activity);
	    interstitial.setAdUnitId(SINGLE_PLAYER_INTERSITIAL_MY_AD_UNIT_ID );
	    interstitial.setAdListener(new AdListener() {
	        @Override
	        public void onAdFailedToLoad(int errorCode) {
	        	openNextImage();
	        }	        
	        @Override
	        public void onAdClosed() {
	        	openNextImage();
	        }
	    });
	    AdRequest adRequest = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();
	    interstitial.loadAd(adRequest);
	}
	public void createQuestionsPopup(RandomImageEnvelope envelope) {	
		this.envelope = envelope;
		this.questionAnswered = false;
		LinkedList<Integer> listOfAnswerIDs = new LinkedList<Integer>(); 
		listOfAnswerIDs.add(R.id.answer1);
		listOfAnswerIDs.add(R.id.answer2);
		listOfAnswerIDs.add(R.id.answer3);
		listOfAnswerIDs.add(R.id.answer4);
		ListUtils.shuffleList(listOfAnswerIDs);
		
		View view = activity.getLayoutInflater().inflate(R.layout.activity_question, null);
		TextView question = (TextView)view.findViewById(R.id.question);
		question.setText(envelope.getQuestion());
		
		correct = (RelativeLayout)view.findViewById(listOfAnswerIDs.removeFirst());
		incorrect1 = (RelativeLayout)view.findViewById(listOfAnswerIDs.removeFirst());
		incorrect2 = (RelativeLayout)view.findViewById(listOfAnswerIDs.removeFirst());
		incorrect3 = (RelativeLayout)view.findViewById(listOfAnswerIDs.removeFirst());
		//resizeLayouts();

		correctTextView = ((TextView)correct.getChildAt(1));
		incorrect1TextView = ((TextView)incorrect1.getChildAt(1));
		incorrect2TextView = ((TextView)incorrect2.getChildAt(1));
		incorrect3TextView = ((TextView)incorrect3.getChildAt(1));

		String rightAnswer = envelope.getRigthAnswer();
		String wrongAnswer1 = envelope.getWrongAnswer1();
		String wrongAnswer2 = envelope.getWrongAnswer2();
		String wrongAnswer3 = envelope.getWrongAnswer3();

		correctTextView.setText(rightAnswer);
		incorrect1TextView.setText(wrongAnswer1);
		incorrect2TextView.setText(wrongAnswer2);
		incorrect3TextView.setText(wrongAnswer3);
		
//		StringUtils.formatStringAnswer(rightAnswer, correctTextView);
//		StringUtils.formatStringAnswer(wrongAnswer1, incorrect1TextView);
//		StringUtils.formatStringAnswer(wrongAnswer2, incorrect2TextView);
//		StringUtils.formatStringAnswer(wrongAnswer3, incorrect3TextView);
//		StringUtils.setUnifiedTextSize(activity); 

		//CORRECT 1
		correct.setBackgroundColor(GRAY);
		correct.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				if (!questionAnswered){
					questionCorrectAnswer(v);
					correct.setBackgroundColor(GREEN);
				}
			}
		});
		//INCORRECT 1
		incorrect1.setBackgroundColor(GRAY);
		incorrect1.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				if (!questionAnswered){
					questionIncorrectAnswer(v);
					correct.setBackgroundColor(GREEN);
				}
			}
		});
		//INCORRECT 2
		incorrect2.setBackgroundColor(GRAY);
		incorrect2.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				if (!questionAnswered){
					questionIncorrectAnswer(v);
					correct.setBackgroundColor(GREEN);
				}
			}
		});
		//INCORRECT 3
		incorrect3.setBackgroundColor(GRAY);
		incorrect3.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				if (!questionAnswered){
					questionIncorrectAnswer(v);
					correct.setBackgroundColor(GREEN);
				}
			}
		});
		
		timerTextView = (TextView)view.findViewById(R.id.timerTextView);
		puntajeTextView = (TextView)view.findViewById(R.id.puntajeTextView);
		AlertDialog.Builder builder = new AlertDialog.Builder(activity);
	    builder.setView(view);
	    builder.setCancelable(false);
	    dialog = builder.create();
		dialog.setOnDismissListener(new OnDismissListener() {			
			@Override
			public void onDismiss(DialogInterface dialog) {
				try {
					ServerConnector.incrementScore(questionScore,QuestionDialogUtils.this.envelope.getImageID(),false);
					if (MainActivity.userData.shuldShowSinglePlayerAd()){
						if (interstitial.isLoaded()) {
							interstitial.show();
							return;
						}
					}
					openNextImage();
				} catch (ConnectivityException e) {
					ErrorOccurredDialogUtils d = new ErrorOccurredDialogUtils(activity, e);
					d.createErrorOccurredPopup();
					e.printStackTrace();
				}
			}
		});
		dialog.show();
		startTimer();
	}
	public void questionCorrectAnswer(View view){
		SoundsUtils.playSound(activity, R.raw.correct_answer);
		questionAnswered = true;
		Toast.makeText(activity, activity.getString(R.string.correct), Toast.LENGTH_SHORT).show();
		try {
			ServerConnector.incrementScore(questionScore,envelope.getImageID(),false);
		} catch (ConnectivityException e) {
			ErrorOccurredDialogUtils d = new ErrorOccurredDialogUtils(activity, e);
			d.createErrorOccurredPopup();
			e.printStackTrace();
		}
		closeDialog();
	}
	public void questionIncorrectAnswer(View view){
		SoundsUtils.playSound(activity, R.raw.incorrect_answer);
		questionAnswered = true;
		correct.setBackgroundColor(GREEN);
		view.setBackgroundColor(RED);
		Toast.makeText(activity, activity.getString(R.string.incorrect), Toast.LENGTH_SHORT).show();
		try {
			ServerConnector.incrementScore(0,envelope.getImageID(),false);
		} catch (ConnectivityException e) {
			ErrorOccurredDialogUtils d = new ErrorOccurredDialogUtils(activity, e);
			d.createErrorOccurredPopup();
			e.printStackTrace();
		}
		closeDialog();
	}
	private void closeDialog() {
		stopTimer();
		AsyncTask<Void, Void, Void> thread = new AsyncTask<Void, Void, Void>(){
			@Override
			protected Void doInBackground(Void... params) {
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
//					GoogleAnalyticsTracker.trackException(activity, e);
					e.printStackTrace();
				}
				QuestionDialogUtils.this.dialog.dismiss();
				return null;
			}
		};

		if (android.os.Build.VERSION.SDK_INT > 10) {
			thread.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		}else{
			thread.execute();
		}
	}
	private void startTimer(){
		questionScore = SystemConstants.MAX_QUESTION_TIME / (15000);
		timerThread = new AsyncTask<Void, Void, Void>(){
			private int timeElapsed = 0, timeRemaining, minutes, seconds;
			private String minutesString, secondsString;
			@Override
			protected Void doInBackground(Void... params) {
				long lastSystemTime = System.currentTimeMillis();
				while (timeElapsed < SystemConstants.MAX_QUESTION_TIME){					
					timeElapsed += System.currentTimeMillis() - lastSystemTime;
					lastSystemTime = System.currentTimeMillis();
					timeRemaining = SystemConstants.MAX_QUESTION_TIME - timeElapsed;
					seconds = timeRemaining/1000;
					minutes = seconds/60;
					seconds = seconds % 60;
					minutesString = minutes < 10 ? StringPool.ZERO+minutes : String.valueOf(minutes);
					secondsString = seconds < 10 ? StringPool.ZERO+seconds : String.valueOf(seconds);
					questionScore = (seconds/15)+1;
					Runnable r = new Runnable() {
						public void run() {
							if (timeElapsed < SystemConstants.MAX_QUESTION_TIME){
								timerTextView.setText(minutesString+StringPool.S_COLON_S+secondsString);
								puntajeTextView.setText(String.valueOf(questionScore));
							}else{
								Toast.makeText(activity, activity.getString(R.string.image_base_activity_time_up), Toast.LENGTH_SHORT).show();
								SoundsUtils.playSound(activity, R.raw.incorrect_answer);
								closeDialog();
							}
						}
					};
					activity.runOnUiThread(r);
					try {
						Thread.sleep(200);
					} catch (Exception e) {
//						GoogleAnalyticsTracker.trackException(activity, e);
						e.printStackTrace();
						break;
					}
				}
				return null;
			}
		};

		if (android.os.Build.VERSION.SDK_INT > 10) {
			timerThread.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		}else{
			timerThread.execute();
		}
	}
	private void stopTimer(){
		timerThread.cancel(true);
	}

	private void openNextImage(){
		Intent i = new Intent(activity.getApplicationContext(), SinglePlayerImage.class);
		i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_TOP);
		SinglePlayerImage.reset();
		EnlargeImageDialogUtils.reset();
		activity.startActivity(i);
		activity.finish();
	}
}
